import React, { useRef, useState, useEffect } from "react";
import "./index.scss";
import { useDispatch, useSelector } from "react-redux";
import { fetchImgItems } from "@/store/modules/images";

const ScrollBig = () => {
  const dispatch = useDispatch();
  const images = useSelector((state) => state.images.items);
  const scrollRef = useRef(null);
  useEffect(() => {
    dispatch(fetchImgItems());
  }, [dispatch]);
  const [showLeftArrow, setShowLeftArrow] = useState(false);
  const [showRightArrow, setShowRightArrow] = useState(true);

  // 滚动检查显示哪个箭头
  const checkArrows = () => {
    const el = scrollRef.current;
    if (!el) return;
    const { scrollLeft, scrollWidth, clientWidth } = el;

    setShowLeftArrow(scrollLeft > 5); // 滚动距离大于5才显示左箭头
    setShowRightArrow(scrollLeft + clientWidth < scrollWidth - 5); // 还能往右滚动才显示右箭头
  };

  useEffect(() => {
    checkArrows();
    const el = scrollRef.current;
    if (!el) return;
    el.addEventListener("scroll", checkArrows);
    return () => el.removeEventListener("scroll", checkArrows);
  }, []);

  // 点击右箭头，往右滚动 120px（卡片宽度+间距）
  const scrollRight = () => {
    scrollRef.current.scrollBy({ left: 132, behavior: "smooth" });
  };

  // 点击左箭头，往左滚动 120px
  const scrollLeft = () => {
    scrollRef.current.scrollBy({ left: -132, behavior: "smooth" });
  };

  return (
    <div className="images-ss">
      <button className="arrow-btn left" onClick={scrollLeft}>
        &#10094;
      </button>
      <div className="scroll-wrapper" ref={scrollRef}>
        {images.map((item, index) => (
          <div className="image-lock" key={index}>
            <img
              style={{ height: 320, width: 290, borderRadius: "14px" }}
              src={item.image}
            />
            <div className="header-top">
              <div className="header-san">
                <div className="san-top">{item.tit}</div>
                <div
                  className="san-topn"
                  style={{ color: index === 0 ? "#fff" : "#000" }}
                >
                  {item.title}
                </div>
                <div
                  className="san-cont"
                  style={{ color: index === 0 ? "#fff" : "#000" }}
                >
                  {item.name}
                </div>
                <div
                  className="san-bot"
                  style={{ color: index === 0 ? "#fff" : "#000" }}
                >
                  {item.info}
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      <button className="arrow-btn right" onClick={scrollRight}>
        &#10095;
      </button>
    </div>
  );
};
export default ScrollBig;
